<!-- 用户管理 -->
<template>
  <div class="app-container flex-row">
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:280px">
      <organization-tree v-model="listQuery.orgId" @selectedOrg="handleSelectedOrg" />
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item>
            <el-input v-model="listQuery.realName" placeholder="请输入真实姓名" class="filter-item" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.mobile" placeholder="请输入手机号" class="filter-item" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.userName" placeholder="请输入用户名" class="filter-item" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--列表-->
      <div class="table-container flex-main">

        <div class="table-container-header">
          <el-tabs v-model="listQuery.isInner" @tab-click="handleTabClick">
            <el-tab-pane label="内部员工" name="1" />
            <el-tab-pane label="外部员工" name="0" />
          </el-tabs>
          <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
            <template slot="rightTool">
              <el-checkbox v-model="listQuery.includeChildren" style="line-height: 33px;">是否包含下级部门</el-checkbox>
              <el-tooltip class="item" effect="dark" content="显示在库所有用户" placement="top">
                <el-button circle icon="el-icon-user" @click="handleGoAllUser" />
              </el-tooltip>
            </template>
          </table-toolbar>
        </div>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          height="100%"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @sort-change="sortChange">
          <el-table-column :selectable="selectable" type="selection" width="50" align="center" />
          <el-table-column align="center" prop="id" width="60" label="#">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="头像" prop="avatar" width="70" align="center">
            <template slot-scope="scope">
              <img :src="common.getFileView(scope.row.avatar)" class="common-round-image-32" data-default="avatar" @error="handleImageError">
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="用户名" prop="userName" width="100">
            <template slot-scope="scope">
              <span class="color-primary common-cursor" @click="handleLookDetails(scope.row)">{{ scope.row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="员工号" width="100" prop="userCode" sortable />
          <el-table-column :show-overflow-tooltip="true" label="姓名" prop="realName" width="100" />
          <el-table-column label="性别" prop="gender" width="80" align="center">
            <template slot-scope="scope">{{ scope.row.gender==1 ?'男': scope.row.gender==2 ? '女' : '保密' }}</template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="手机" prop="mobile" width="110" />
          <el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email" width="150" />
          <el-table-column label="角色" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <template v-if="scope.row.roleName">
                <div v-for="item in scope.row.roleName.split('，')" :key="item" class="color-primary">  {{ item }} </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="加入部门" min-width="280" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-for="item in scope.row.organizationUsers" :key="item.organizationId" :class="item.organizationType===1?'color-primary':'color-default'">  {{ item._fullOrgName }} </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" prop="isLocked" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isLocked"
                @change="changeIsLocked(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="gmtCreated" width="150" sortable label="录入时间">
            <template slot-scope="scope">{{ scope.row.gmtCreated | formatDate }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <div v-if="userInfo.id==scope.row.id">
                <el-tag>当前</el-tag>
              </div>
              <div v-if="userInfo.id!=scope.row.id">
                <button-option icon="el-icon-lock" skin="primary" title="初始化密码" @click="initialPasswordSingle(scope.row)" />
                <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
                <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" width="700px" :title="sideBox.title" @close="sideBox.recordShow=!sideBox.recordShow">
      <template slot="body">
        <el-form ref="dataForm" :rules="recordRules" :model="userRecord" label-position="right" label-width="120px">
          <div class="common-title m-b-20"><h2 class="bold">基本信息</h2></div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名:" prop="realName">
                <el-input v-model="userRecord.realName" :disabled="sideBox.status!=='create'" maxlength="10" show-word-limit placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型:" prop="category">
                <data-dict-select v-model="userRecord.category" code="userCategory" placeholder="请选择用户类型" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机:" prop="mobile">
                <el-input v-model="userRecord.mobile" maxlength="11" show-word-limit placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号:" prop="userName">
                <el-input v-model="userRecord.userName" :disabled="sideBox.status!=='create'" maxlength="11" show-word-limit placeholder="请输入账号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别:" prop="gender">
                <el-radio-group v-model="userRecord.gender">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="微信:" prop="weixin">
                <el-input v-model="userRecord.weixin" show-word-limit placeholder="请输入微信" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱:" prop="email">
                <email-input-select v-model="userRecord.email" placeholder="请输入电子邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="座机:" prop="phone">
                <el-input v-model="userRecord.phone" maxlength="15" show-word-limit placeholder="请输入座机号码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="证件号码:" prop="idNumber">
            <el-input v-model="userRecord.idNumber" maxlength="18" show-word-limit placeholder="请输入证件号码" />
          </el-form-item>
          <div class="common-title m-b-20"><h2 class="bold">三方账号</h2></div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="钉钉:">
                <span v-if="userRecord.dingTalkUserId" class="color-primary">{{ userRecord.dingTalkUserId }}</span>
                <span v-if="!userRecord.dingTalkUserId" class="color-danger">使用钉钉扫码登录系统自动绑定!</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业微信标识:" prop="wxWorkUserId">
                <el-input v-model="userRecord.wxWorkUserId" maxlength="15" show-word-limit placeholder="请输入企业微信用户标识" />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="common-title m-b-20"><h2 class="bold">员工信息</h2></div>
          <el-form-item v-if="sideBox.status==='create'" label="加入部门:">{{ userRecord.userOrganization.fullOrganizationName }}
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="内部员工:" prop="isInner">
                <el-radio-group v-model="userRecord.isInner">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通讯录:" prop="isAddMailList">
                <el-radio-group v-model="userRecord.isAddMailList">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="员工编号:" prop="userCode">
                <el-input v-model="userRecord.userCode" :disabled="sideBox.status!=='create'" maxlength="7" show-word-limit placeholder="请输入员工编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职位:" prop="userOrganization.job">
                <el-input v-model="userRecord.userOrganization.job" maxlength="30" show-word-limit placeholder="请输入员工职位" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="办公室座机:" prop="userOrganization.phone">
                <el-input v-model="userRecord.userOrganization.phone" show-word-limit placeholder="请输入办公室座机" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序:" prop="userOrganization.orders">
                <template slot="label">
                  排序
                  <el-tooltip class="item" effect="dark" content="值越大越靠前" placement="bottom">
                    <i class="el-icon-question" />
                  </el-tooltip>
                </template>
                <el-input-number v-model="userRecord.userOrganization.orders" placeholder="请输入排序" show-word-limit :min="1" :max="9999" style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="角色" prop="userRole">
            <div v-for="group in roleList" :key="group.id">
              <el-checkbox
                :label="group.name"
                disabled>
                {{ group.name }}
              </el-checkbox>
              <el-checkbox-group v-model="userRecord.userRole">
                <el-checkbox
                  v-for="item in group.children"
                  :key="item.id"
                  :label="item.id"
                  :value="item.id">{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <el-empty v-if="roleList.length===0" description="暂无可用角色" />

          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" @click="sideBox.status==='create'?createData():updateData()">确定</el-button>
      </template>
    </side-box>
    <user-details ref="userDetails" />
  </div>
</template>

<script>

export default {
  components: { },
  data() {
    var checkUsertName = (rule, value, callback) => {
      this.$store.dispatch('userValidateExistByField', { id: this.userRecord.id, field: 'userName', value: value }).then(response => {
        if (response) {
          return callback(new Error('用户名已存在，请重新输入'))
        } else {
          return callback()
        }
      }).catch((_) => { })
    }
    var checkUsertMobile = (rule, value, callback) => {
      this.$store.dispatch('userValidateExistByField', { id: this.userRecord.id, field: 'mobile', value: value }).then(response => {
        if (response) {
          return this.handleUserMobileExist(callback, value)
        } else {
          return callback()
        }
      }).catch((_) => { })
    }
    return {
      selectedOrg: {},
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        includeChildren: true,
        realName: '',
        mobile: '',
        userName: '',
        isInner: '1'
      },
      multipleSelectionRecords: [],
      roleList: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },

      userRecord: {
        userRole: [],
        userOrganization: {
        }
      },
      recordRules: {
        category: [
          { required: true, message: '请选择用户分类', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { required: true, validator: checkUsertName, trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { validator: this.$validate.validateRealName, trigger: 'blur' }
        ],
        email: [
          { validator: this.$validate.validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: this.$validate.validateMobile, trigger: 'blur' },
          { required: true, validator: checkUsertMobile, trigger: 'blur' }
        ],
        userCode: [
          { min: 7, max: 7, message: '必须是7个字符', trigger: 'blur' }
        ],
        idNumber: [
          { validator: this.$validate.validateIDCard, trigger: 'blur' }
        ],
        'userOrganization.orders': [
          { required: true, message: '请输入员工排序', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {

  },
  watch: {
    'listQuery.orgId'(val) {
      if (val) {
        this.handleReset()
      }
    },
    'listQuery.includeChildren'(val) {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    'userRecord.idNumber': function(val) {
      if (val) {
        var res = this.T.analyzeIDCard(val)
        if (res) {
          this.userRecord = {
            ...this.userRecord,
            gender: res.sex
          }
        } else {
          this.userRecord = {
            ...this.userRecord,
            gender: 1
          }
        }
      }
    }
  },
  created() {
  },
  methods: {
    handleSelectedOrg(data) {
      this.selectedOrg = data
    },
    handleTabClick() {
      this.handleReset()
    },
    roleTree() {
      this.$store.dispatch('roleTreeTable', {}).then((res) => {
        this.roleList = res
      }).catch((_) => {})
    },

    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    selectable(row) {
      if (row.id !== this.userInfo.id) {
        return true
      } else {
        return false
      }
    },

    async fetchData() {
      const response = await this.$store.dispatch('userPageV2', this.listQuery)
      this.list = response.records
      this.list.filter((item) => {
        item.isLocked = !item.isLocked
        return true
      })
      this.total = response.total
    },
    // 固定写法
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 固定写法
    handleCommand(val) {
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        realName: '',
        mobile: '',
        userName: ''
      }
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    /* 新增*/
    handleCreate() {
      this.roleTree()
      this.userRecord = {
        userCode: this.T.randomNumber(7),
        gender: 1,
        isInner: 1,
        isAddMailList: 1,
        userRole: [],
        userOrganization: {
          orders: 9999,
          fullOrganizationName: this.selectedOrg.fullPathName,
          organizationId: this.selectedOrg.id
        }
      }
      console.log(this.userRecord)
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增用户'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      const temp = Object.assign({}, this.userRecord)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          temp.roles = temp.userRole
          delete temp.userRole
          this.$store.dispatch('userSave', temp).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    async handleLookDetails(row) {
      this.$refs.userDetails.init(row.id)
    },
    /* 编辑*/
    async handleUpdate(row) {
      this.roleTree()
      this.formEcho(row.id)
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: '编辑用户[' + row.userName + ']'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const tempData = Object.assign({}, this.userRecord)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          tempData.roles = tempData.userRole
          delete tempData.userRole
          delete tempData.upmsOrganizations
          this.$store.dispatch('userUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        let isDelted = true
        const ids = []
        this.multipleSelectionRecords.forEach((v, i) => {
          if (this.$store.getters.userInfo.id === v.id) {
            this.$modal.msgWarning('自己不能删除当前用户')
            isDelted = false
          }
          ids.push(v.id)
        })
        if (isDelted) {
          this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('userRemove', ids).then(response => {
              this.handleReset()
              this.$modal.msgSuccess('删除成功')
            }).catch(() => { })
          }).catch(() => { })
        }
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    async handleUserMobileExist(callback, mobile) {
      var res = await this.$store.dispatch('getUserByMobile', mobile)
      var organizations = res.organizations
      var userTip = `${res.user.mobile}`
      if (res.user.realName) {
        userTip += `(${res.user.realName})`
      }
      var tips = `系统检测出用户【${userTip}】已存在系统但未加入任何组织，是否将该用户加入到所选组织?`
      if (organizations.length > 0) {
        var tempOrg = []
        if (organizations) {
          organizations.forEach(item => {
            tempOrg.push(item._fullOrgName)
          })
        }
        tips = `系统检测出用户【${userTip}】已加入【${tempOrg.join('、')}】等${tempOrg.length}个组织, 是否继续?`
      }

      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.sideBox = {
          ...this.sideBox,
          status: 'update',
          title: '编辑用户[' + res.user.userName + ']'
        }
        this.userRecord = {
          ...res.user,
          userRole: [],
          userOrganization: {
            orders: 9999,
            fullOrganizationName: this.selectedOrg.fullPathName,
            organizationId: this.selectedOrg.id
          }
        }
        if (res.roles.length > 0) {
          var userRoles = []
          res.roles.forEach((item) => {
            userRoles.push(item.id)
          })
          this.userRecord = {
            ...this.userRecord,
            userRole: userRoles
          }
        }
      }).catch(() => {
        return callback(new Error('用户名已存在，请重新输入'))
      })
    },
    async formEcho(id) {
      const res = await this.$store.dispatch('getUserDetailsById', id)
      /**
       * 此地方还需要优化
       */
      var org = {}
      var organizations = res.organizations
      if (organizations) {
        var temp = organizations.filter(item => {
          return item.id === this.listQuery.orgId
        })
        if (temp.length === 0) {
          this.$modal.msgWarning('请前往该用户直属部门修改信息')
          this.sideBox = {
            ...this.sideBox,
            recordShow: false
          }
          return
        }
        if (temp.length > 0) {
          org = {
            orders: temp[0].orders,
            phone: temp[0].orgPhone,
            job: temp[0].orgJob,
            organizationId: temp[0].id
          }
        }
      }
      this.userRecord = {
        ...res.user,
        userRole: [],
        userOrganization: org
      }
      if (res.roles.length > 0) {
        var userRoles = []
        res.roles.forEach((item) => {
          userRoles.push(item.id)
        })
        this.userRecord = {
          ...this.userRecord,
          userRole: userRoles
        }
      }
    },

    /**
      * 用户启用和禁用
    */
    changeIsLocked(row) {
      var temp = Object.assign({}, row) // copy obj

      this.$confirm('您确定' + (temp.isLocked === false ? '禁用' : '启用') + '用户[' + temp.userName + '], 是否继续?', '系统提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        const params = {
          isLocked: !temp.isLocked,
          id: temp.id
        }
        this.$store.dispatch('changeIsLocked', params).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.handleFilter()
        }).catch(() => {
          row.isLocked = !row.isLocked
        })
      }).catch(() => {
        row.isLocked = !row.isLocked
      })
    },
    initialPasswordSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.initialPassword()
    },
    initialPassword() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$store.dispatch('initialPassword', ids).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response)
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要初始化密码的记录')
      }
    },
    handleGoAllUser() {
      this.$router.push({ name: 'userAllManager' })
      const view = this.$route
      delete view.icon
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {})
    }
  }
}
</script>
<style lang="scss" scoped>
</style>

